<template>
    <div class="dictionary">
        <div class="page-search">
            <div>
                <el-input v-model="search.title" placeholder="名称"></el-input>
            </div>
            <div>
                <el-input v-model="search.only_key" placeholder="唯一标识"></el-input>
            </div>
            <div>
                <el-button type="primary" @click="getList">查询</el-button>
            </div>
        </div>
        <div class="page-action-btn">
            <el-button v-if="auth.add" type="primary" @click="showAdd">添加</el-button>
            <el-button v-if="auth.edit" type="warning" @click="showEdit">修改</el-button>
            <p-confirm-btn v-if="auth.del" @confirm="del"></p-confirm-btn>
        </div>
        <p-table v-if="auth.get" v-loading="loading" :data="dataList" :sub-height="220" :show-paginate="true" v-model="paginate" :highlight-current-row="true" @paginate="getList" :checkBox="false"
            @row-click="rowClick" @row-dblclick="rowDblclick" @row-clear="rowClear">
            <el-table-column prop="title" label="名称" min-width="160"></el-table-column>
            <el-table-column prop="only_key" label="唯一标识" min-width="150"></el-table-column>
            <el-table-column prop="multiple" label="数据类型" min-width="70">
                <template v-slot="{row}">
                    <div>
                        <el-tag size="small" effect="plain" v-if="row.multiple==2">多数据</el-tag>
                        <el-tag size="small" type="success" effect="plain" v-if="row.multiple==1">单数据</el-tag>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="int_type" label="值类型" min-width="80">
                <template v-slot="{row}">
                    <div>
                        <el-tag size="small" type="warning" effect="plain" v-if="row.int_type==1">字符</el-tag>
                        <el-tag size="small" type="success" effect="plain" v-if="row.int_type==2">整数</el-tag>
                        <el-tag size="small" effect="plain" v-if="row.int_type==3">小数</el-tag>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="enable" label="状态" min-width="70">
                <template v-slot="{row}">
                    <div>
                        <el-tag size="small" effect="plain" v-if="row.enable==1">正常</el-tag>
                        <el-tag size="small" type="danger" effect="plain" v-if="row.enable==2">禁用</el-tag>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" min-width="80"></el-table-column>
            <el-table-column prop="desc" label="备注" min-width="120"></el-table-column>
        </p-table>

        <p-el-dialog v-model="showDialog" :title="`${isEdit?'修改':'添加'}${title}`" width="800px" @close="dialogClose" @confirm="isEdit?edit():add()" :ok-text="isEdit?'修改':'添加'">
            <el-form :model="params" status-icon :rules="paramsRules" ref="elForm" label-width="120px">
                <el-form-item label="名称" prop="title">
                    <el-input v-model="params.title" placeholder="名称"></el-input>
                </el-form-item>
                <el-form-item label="唯一标识" prop="only_key">
                    <el-input v-model="params.only_key" placeholder="唯一标识（由字母，数字，下划线，横线组成）"></el-input>
                </el-form-item>
                <el-form-item label="排序">
                    <el-input v-model="params.sort" placeholder="排序"></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input type="textarea" :row="2" v-model="params.desc" placeholder="请输入备注"></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="enable">
                    <el-radio-group v-model="params.enable" size="small">
                        <el-radio-button :label="1">正常</el-radio-button>
                        <el-radio-button :label="2">禁用</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="数据类型" prop="int_type">
                    <el-radio-group v-model="params.int_type" size="small">
                        <el-radio-button :label="1">字符</el-radio-button>
                        <el-radio-button :label="2">整数</el-radio-button>
                        <el-radio-button :label="3">小数</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="多值" prop="multiple">
                    <el-radio-group v-model="params.multiple" size="small">
                        <el-radio-button :label="1">单个值</el-radio-button>
                        <el-radio-button :label="2">多个值</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <div v-if="params.multiple==1">
                    <div class="multiple">
                        <div>
                            <div>数据标签</div>
                            <div>
                                <el-input v-model="params.value.label" placeholder="请输入数据标签"></el-input>
                            </div>
                        </div>
                        <div>
                            <div>数据值</div>
                            <div v-if="params.int_type==1">
                                <el-input v-model="params.value.str_value" placeholder="请输入数据值"></el-input>
                            </div>
                            <div v-if="params.int_type==2">
                                <el-input v-model="params.value.int_value" oninput="this.value = this.value.replace(/[^\d]/g,'');" placeholder="请输入数据值"></el-input>
                            </div>
                            <div v-if="params.int_type==3">
                                <el-input v-model="params.value.float_value" oninput="this.value = this.value.replace(/[^\d.]/g,'');" placeholder="请输入数据值"></el-input>
                            </div>
                        </div>
                        <div>
                            <div>文本颜色</div>
                            <div>
                                <el-color-picker v-model="params.value.txt_color" show-alpha></el-color-picker>
                            </div>
                        </div>
                        <div>
                            <div>背景颜色</div>
                            <div>
                                <el-color-picker v-model="params.value.background_color" show-alpha></el-color-picker>
                            </div>
                        </div>
                    </div>
                </div>
                <div v-if="params.multiple==2">
                    <div class="multiples">
                        <div class="add" @click="addValues">
                            <i class="el-icon-circle-plus"></i>
                        </div>
                        <el-table :data="params.values" border height="300">
                            <el-table-column label="数据标签" min-width="120">
                                <template v-slot="{row}">
                                    <div class="value-input">
                                        <input v-model="row.label" placeholder="请输入数据标签" />
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="数据值" min-width="100">
                                <template v-slot="{row}">
                                    <div class="value-input">
                                        <div v-if="params.int_type==1">
                                            <input v-model="row.str_value" placeholder="请输入数据值" />
                                        </div>
                                        <div v-if="params.int_type==2">
                                            <input v-model="row.int_value" oninput="this.value = this.value.replace(/[^\d]/g,'');" placeholder="请输入数据值" />
                                        </div>
                                        <div v-if="params.int_type==3">
                                            <input v-model="row.float_value" oninput="this.value = this.value.replace(/[^\d.]/g,'');" placeholder="请输入数据值" />
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="文本颜色" width="90">
                                <template v-slot="{row}">
                                    <div class="value-color">
                                        <el-color-picker v-model="row.txt_color" show-alpha></el-color-picker>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="背景颜色" width="90">
                                <template v-slot="{row}">
                                    <div class="value-color">
                                        <el-color-picker v-model="row.background_color" show-alpha></el-color-picker>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="90">
                                <template v-slot="{$index}">
                                    <div class="delValues">
                                        <div @click="delValues($index)"><i class="el-icon-delete-solid"></i></div>
                                        <div @click="ValuesSort($index,-1)" v-if="$index>0"><i class="el-icon-top"></i></div>
                                        <div @click="ValuesSort($index,1)" v-if="$index < params.values.length-1"><i class="el-icon-bottom"></i></div>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </el-form>
        </p-el-dialog>
    </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, ref, onMounted } from "vue";
import { useStore } from "vuex";
import { IPaginate, defaultPaginate } from "@/lib/IApp";
import PTable from "@/components/PTable.vue";
import PConfirmBtn from "@/components/PConfirmBtn.vue";
import PElDialog from "@/components/PElDialog.vue";
import utils from "@/lib/utils";
import { pHttp } from "@/lib/http/http";
import message from "@/lib/message";
/**
 * state 数据类型
 */
interface IState {
    loading: boolean;
    paginate: IPaginate;
    /**
     * 数据列表
     */
    dataList: any[];
    /**
     * 是否显示 添加编辑窗口
     */
    showDialog: boolean;
    /**
     * 是否修改
     */
    isEdit: boolean;
    /**
     * http 请求参数
     */
    params: any;
    /**
     * 单选选择的行内容
     */
    tableRow: any;
    search: any;
}
export default defineComponent({
    name: "Dictionary",
    components: { PTable, PConfirmBtn, PElDialog },
    props: {
        url: {
            type: String,
            default: "dictionary"
        },
        title: {
            type: String,
            default: "字典"
        },
        auth: {
            type: Object,
            default: () => ({
                add: true,
                del: true,
                edit: true,
                get: true
            })
        }
    },
    setup(props) {
        const store = useStore();
        const { UIAuth, bodySize } = toRefs(store.state);
        const pTable: any = ref<any>();
        const elForm: any = ref<any>();
        /**
         * 参数校验
         */
        const paramsRules = {
            title: [
                {
                    required: true,
                    message: "请输入" + props.title + "名称",
                    trigger: ["blur", "change"],
                },
            ],
            only_key: [
                {
                    required: true,
                    message: "请输入" + props.title + "唯一标识",
                    trigger: ["blur", "change"],
                },
            ],
            enable: [
                {
                    required: true,
                    message: "请选择" + props.title + "状态",
                    trigger: ["blur", "change"],
                },
            ],
            int_type: [
                {
                    required: true,
                    message: "请选择" + props.title + "值类型",
                    trigger: ["blur", "change"],
                },
            ],
            multiple: [
                {
                    required: true,
                    message: "请选择" + props.title + "是否多值",
                    trigger: ["blur", "change"],
                },
            ],
        };
        const defaultValue = { label: "", str_value: "", int_value: "", float_value: "", txt_color: "#000000", background_color: "#FFFFFF" };
        const defaultParams = { sort: 1, enable: 1, int_type: 1, multiple: 2, value: utils.CopyNewObject(defaultValue), values: [] };
        const state = reactive<IState>({
            loading: false,
            paginate: defaultPaginate,
            dataList: [],
            showDialog: false,
            isEdit: false,
            params: utils.CopyNewObject(defaultParams),
            tableRow: null,
            search: {}
        });
        /**
         * 删除
         */
        function del() {
            if (utils.empty(state.tableRow)) {
                return message.error("请选择要删除的数据");
            }
            message.loadingShow("删除中");
            pHttp.Delete("/" + props.url, { ids: [state.tableRow.id] })
                .then((data) => {
                    const index = state.dataList.findIndex((i: any) => i.id === state.tableRow.id);
                    if (index >= 0) {
                        state.dataList.splice(index, 1);
                    }
                    state.tableRow = null;
                })
                .catch((err) => false);
        }
        /**
         * 显示添加
         */
        function showAdd() {
            state.params = utils.CopyNewObject(defaultParams);
            state.isEdit = false;
            state.showDialog = true;
        }
        /**
         * 显示修改
         */
        function showEdit() {
            if (state.tableRow) {
                state.params = {
                    id: state.tableRow.id,
                    title: state.tableRow.title,
                    only_key: state.tableRow.only_key,
                    type: state.tableRow.type,
                    multiple: state.tableRow.multiple,
                    int_type: state.tableRow.int_type,
                    value: utils.CopyNewObject(state.tableRow.value),
                    values: utils.CopyNewObject(state.tableRow.values),
                    enable: state.tableRow.enable,
                    sort: state.tableRow.sort,
                    desc: state.tableRow.desc,
                };
                state.isEdit = true;
                state.showDialog = true;
            } else {
                message.error("请选择要修改数据");
            }
        }
        /**
         * 关闭添加编辑窗口
         */
        function dialogClose() {
            state.params = utils.CopyNewObject(defaultParams);
            state.isEdit = false;
            state.showDialog = false;
        }
        function add() {
            elForm.value.validate((ok: boolean) => {
                if (ok) {
                    message.loadingShow("保存中");
                    pHttp.Post("/" + props.url, state.params)
                        .then((data) => {
                            if (state.dataList && state.dataList.length > 0) {
                                state.dataList.unshift(data);
                            } else {
                                state.dataList = [data];
                            }
                            dialogClose();
                        })
                        .catch((err) => "");
                } else {
                    return false;
                }
            });
        }
        function edit() {
            elForm.value.validate((ok: boolean) => {
                if (ok) {
                    message.loadingShow("修改中");
                    pHttp.Put("/" + props.url, state.params)
                        .then((data) => {
                            const index = state.dataList.findIndex((i: any) => i.id === data.id);
                            if (index >= 0) {
                                state.dataList.splice(index, 1, data);
                            }
                            dialogClose();
                        })
                        .catch((err) => "");
                } else {
                    return false;
                }
            });
        }
        // 添加数据
        function addValues() {
            state.params.values.push(utils.CopyNewObject(defaultValue));
        }
        // 删除数
        function delValues(index: number) {
            state.params.values.splice(index, 1);
        }
        // 获取数据
        function getList() {
            state.loading = true;
            pHttp.Get("/" + props.url + `/${state.paginate.page_size}/${state.paginate.page}`, state.search)
                .then((data) => {
                    state.dataList = data.data;
                    state.paginate = data.paginate;
                    state.loading = false;
                })
                .catch((err) => state.loading = false);
        }
        //
        function rowClick({ row }: any) {
            state.tableRow = row;
        }
        function rowDblclick({ row }: any) {
            state.tableRow = row;
            showEdit();
        }
        function rowClear() {
            state.tableRow = null;
        }
        function ValuesSort(index: number = 0, step: number = 0) {
            const netxIndex = index + step;
            if (netxIndex >= 0 && netxIndex < state.params.values.length && netxIndex !== index) {
                const tem = utils.CopyNewObject(state.params.values[netxIndex]);
                state.params.values[netxIndex] = utils.CopyNewObject(state.params.values[index]);
                state.params.values[index] = tem;
            }
        }
        onMounted(() => {
            getList();
        });
        return {
            UIAuth,
            bodySize,
            del,
            showAdd,
            ...toRefs(state),
            paramsRules,
            showEdit,
            dialogClose,
            add,
            edit,
            addValues,
            delValues,
            pTable,
            elForm,
            getList,
            rowClick,
            rowDblclick,
            rowClear,
            ValuesSort
        };
    },
});
</script>

<style lang="scss">
.dictionary {
}
.multiple {
    padding:0 10px;
    margin-left: 80px;
    & > div {
        //flex: 1;
        display: flex;
        align-items: center;
        padding: 5px 0;
        & > div {
            &:first-child {
                width: 80px;
                text-align: right;
                padding-right: 10px;
            }
        }
    }
}
.multiples {
    position: relative;
    .el-table td {
        padding: 0;
    }
    .el-table .cell {
        padding-left: 0;
        padding-right: 0;
    }
    .el-table--border td:first-child .cell {
        padding-left: 0;
    }
    .el-table--border th .cell {
        padding-left: 15px;
        padding-right: 15px;
    }
    & .add {
        position: absolute;
        right: 5px;
        top: 7px;
        z-index: 99;
        font-size: 20px;
        color: $link-color;
    }
}
.value-color {
    display: flex;
    align-items: center;
    justify-content: center;
}
.delValues {
    font-size: 16px;
    display: flex;
    align-items: center;
    & > div {
        width: 33%;
        text-align: center;
        &:nth-child(1) {
            color: #c74b3d;
        }
        &:nth-child(2) {
            color: $link-color;
        }
        &:nth-child(3) {
            color: $link-color;
        }
    }
}
.value-input {
    input {
        width: 100%;
        height: 38px;
        border: none;
        padding: 0 15px;
    }
}
</style>
